package br.com.center.loja.ws;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/father")
public class FatherResource {
	
	private static final int MIN = 2;
    private static final int MAX = 5;
	
	@GET
	@Produces({MediaType.APPLICATION_JSON})
	public List<Father> get(){
		List<Father> fathers = new ArrayList<Father>();
		
		int qtde = (int) (Math.random() * (MAX - MIN + 1) ) + MIN;
		
		for( int i = 0; i < qtde; i++ ){
			fathers.add(create());
		}
		
		return fathers;
	}
	
	@Path("/save")
	@POST
	@Consumes({MediaType.APPLICATION_JSON})
	@Produces({MediaType.TEXT_PLAIN})
	public String save(Father father){
		try {
			System.out.println("vai salvar...");
			System.out.println("father: " + father.getCode() + 
					" - " + father.getName());
			List<Son> sons = father.getSons();
			
			for (Son son : sons) {
				System.out.println("son: " + son.getCode() + 
						" - " + son.getName());
			}
			
			return "Dados recebidos e salvos com sucesso!";
		} catch (Exception e) {
			return "Deu algum erro no server ("+e.getMessage()+")";
		}
	}
	
	private Father create(){
		Father father = new Father();
		father.setCode((int)(Math.random()*100));
		father.setName("Nome " + father.getCode());
		
		List<Son> children = new ArrayList<Son>();
		
		int qtde = (int) (Math.random() * (MAX - MIN + 1) ) + MIN;
		
		for( int i = 0; i < qtde; i++ ){
			Son child = new Son();
			child.setCode((int)(Math.random()*100*i));
			child.setName("Nome " + child.getCode());
			children.add(child);
		}
		
		father.setSons(children);
		
		return father;
	}

}
